Skip to content

Move function-local records in global scope - #375

Merged
nunoplopes merged 5 commits into
Cpp2Rust:masterfrom
lucic71:function-local-records
Sep 16, 2026
Merged

nunoplopes merged 5 commits into
Cpp2Rust:masterfrom
lucic71:function-local-records

Conversation

@lucic71

@lucic71 lucic71 commented Sep 16, 2026

Copy link
Copy Markdown
Contributor
template <typename T> int get(T t) { return t.x; }

int main() {
  struct Local {
    int x;
  };
  Local l{7};
  assert(get(l) == 7);
  return 0;
}

The get function template lives in the global scope while Local (used to instantiate get) lives at function scope. In the AST instantiations live in the global scope as well, so it gets translated as:

// Wrong: the global scope has no Local_1. It only exists inside main
pub unsafe fn get_0(mut t: Local_1) -> i32 {
    return (t.x as i32);
}

unsafe fn main_0() -> i32 {
    pub struct Local_1 {
      pub x: i32,
    };
    let mut l: Local_1 = Local_1 { x: 7 };
    assert!(((unsafe { get_0(l,) }) == (7)));
    return 0;
}

This PR fixes this by moving the definition of Local_1 at a global scope:

// Correct: now Local_1 is visible for the instantiation
pub unsafe fn get_0(mut t: Local_1) -> i32 {
    return (t.x as i32);
}

unsafe fn main_0() -> i32 {
    let mut l: Local_1 = Local_1 { x: 7 };
    assert!(((unsafe { get_0(l,) }) == (7)));
    return 0;
}

pub struct Local_1 {
    pub x: i32,
};

@nunoplopes
nunoplopes merged commit 8e84d83 into Cpp2Rust:master Sep 16, 2026
9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants